package cc.comac.mom.service.impl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import cc.comac.mom.api.EquipDocumentManagementService;
import cc.comac.mom.api.QualityAttachmentService;
import cc.comac.mom.bean.EquipDocumentManagement;
import cc.comac.mom.bean.ResultDev;
import cc.comac.mom.config.OSSService;
import cc.comac.mom.datahandlers.entity.EquipDocumentManagementDataHandler;
import cc.comac.mom.entity.EquipDocumentManagementEntity;
import cc.comac.mom.entity.QualityAttachmentEntity;
import cc.comac.mom.util.GetGeneralFieldValue;
import cc.comac.mom.util.ResultBean;
@RestController
@Service
public class EquipDocumentManagementServiceImpl implements EquipDocumentManagementService {


	@Autowired
	private EquipDocumentManagementDataHandler equipDocumentManagementDataHandler;
	@Autowired OSSService oSSService;
	
	@Autowired
	private QualityAttachmentService qualityAttachmentService;
	
	@Override
	// 文件上传简单实现
	public ResultBean saveToServiceNoChunk(@RequestPart("files") MultipartFile files) {
		ResultBean resultBean = new ResultBean(true);
		// 获取文件全名称
		String originalFilename = files.getOriginalFilename();
//		QueryWrapper<EquipDocumentManagementEntity> queryWrapper = new QueryWrapper<EquipDocumentManagementEntity>();
//		queryWrapper.eq("document_name", originalFilename);
//		queryWrapper.eq("row_status", 1);
//		EquipDocumentManagementEntity equipDocumentManagementEntity = equipDocumentManagementDataHandler
//				.getOne(queryWrapper);
//		if (equipDocumentManagementEntity != null) {
//			throw new RuntimeException("当前文件名" + originalFilename + "已存在，无法新增！");
//		}
		String path = "";
		try {
			// 获取文件路径名
			path = oSSService.uploadFileOss(files);
//			String path = rootPath + File.separator + originalFilename;
			// 将文件写入
//			File file2 = new File(path);
//			if (!file2.getParentFile().exists()) {
//				file2.getParentFile().mkdirs();
//			}
			
//			files.transferTo(file2);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}
		Map<String,String> hashMap = new HashMap<String,String>();
		hashMap.put("originalFilename", originalFilename);
		hashMap.put("path", path);
		resultBean.setObject(originalFilename);
		return resultBean;
	}

	@Override
	public ResultBean batchSave(@RequestBody List<EquipDocumentManagement> equipList) {
		ResultBean resultBean = new ResultBean(true);
		List<EquipDocumentManagementEntity> list = new ArrayList<EquipDocumentManagementEntity>();
		for (EquipDocumentManagement equipDocumentManagement2 : equipList) {
			
			QualityAttachmentEntity byAttachmentId = qualityAttachmentService.getByAttachmentId(equipDocumentManagement2.getAttachmentId());
			
			// 获取文件路径名
			String path = byAttachmentId.getFilePath();
			URL url = oSSService.getUrl(path);
			URLConnection openConnection = null;
			int contentLength = 0;
			try {
				openConnection = url.openConnection();
				contentLength = openConnection.getContentLength();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// 保存文档信息
			EquipDocumentManagement equipDocumentManagement1 = new EquipDocumentManagement();
			equipDocumentManagement1.setDocumentName(byAttachmentId.getRealName());
			equipDocumentManagement1.setDocumentSize(byAttachmentId.getFileSize());
			equipDocumentManagement1.setOssDoucumentPath(url.toString());
			equipDocumentManagement1.setDocumentSoure(equipDocumentManagement2.getDocumentSoure());
			equipDocumentManagement1.setCreationTime(GetGeneralFieldValue.getLocalDateTime());
			equipDocumentManagement1.setCreator(GetGeneralFieldValue.getCurrentUser());
			equipDocumentManagement1.setDoucumentRealPath(path);
			equipDocumentManagement1.setRelationId(equipDocumentManagement2.getRelationId());
			list.add(equipDocumentManagement1);
		}
		boolean saveBatch = equipDocumentManagementDataHandler.saveBatch(list, list.size());
		resultBean.setObject(saveBatch);
		return resultBean;
	}

	@Override
	public ResultBean batchDelete(@RequestBody List<EquipDocumentManagement> list) {
		ResultBean resultBean = new ResultBean(true);
		boolean batchDelete = equipDocumentManagementDataHandler.batchDelete(list);
		resultBean.setObject(batchDelete);
		return resultBean;
	}

	@Override
	public ResultDev selectAllByPage(@RequestBody EquipDocumentManagement equipDocumentManagement) {
		ResultDev selectAllByPage = equipDocumentManagementDataHandler.selectAllByPage(equipDocumentManagement);
		return selectAllByPage;
	}

	@Override
	public byte[] previewPdf(@RequestParam long documentId) {
		if (documentId == 0L) {
			throw new RuntimeException("当前未选中数据");
		}
		EquipDocumentManagementEntity byId = equipDocumentManagementDataHandler.getById(documentId);
		InputStream fileByPathFromOss = oSSService.getFileByPathFromOss(byId.getDoucumentRealPath());
		byte[] data = null;
			try {
				data = IOUtils.readFully(fileByPathFromOss, fileByPathFromOss.available());
//				data = new byte[fileByPathFromOss.available()];
//				fileByPathFromOss.read(data);
				fileByPathFromOss.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		return data;
	}

	@Override
	public ResultBean download(Long documentId, HttpServletResponse response) {
		ResultBean resultBean = new ResultBean(true);
		EquipDocumentManagementEntity byId = equipDocumentManagementDataHandler.getById(documentId);
		// 判断是否选中某条数据
		if (byId == null) {
			throw new RuntimeException("未选中数据!");
		}
		// 获取文件上传路径和真实文件名
		String path = byId.getDoucumentRealPath();
		String realName = byId.getDocumentName();
		try {
			// path是指欲下载的文件的路径。
			File file = new File(path);
			// 取得文件名。
			String filename = file.getName();
			// 取得文件的后缀名。
			String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
			// 以流的形式下载文件。
			InputStream fis = new BufferedInputStream(new FileInputStream(path));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			// 清空response
			response.reset();
			// 设置response的Header
			response.addHeader("Content-Disposition",
					"attachment;filename=" + new String(realName.getBytes("UTF-8"), "ISO8859-1"));
			response.addHeader("Content-Length", "" + file.length());
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			toClient.write(buffer);
			toClient.flush();
			toClient.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return resultBean;
	}
	@Override
	public EquipDocumentManagementEntity selectByDocumentId(Long documentId) {
		EquipDocumentManagementEntity byId = equipDocumentManagementDataHandler.getById(documentId);
		return byId;
	}

}
